import { app, BrowserWindow, ipcMain, Menu, Tray, dialog, shell, globalShortcut, Notification } from 'electron'
import { join } from 'path'
import { autoUpdater } from 'electron-updater'
import { settingsManager } from './settings'
import * as http from 'http'

/**
 * RickPan Electron主进程
 * 负责窗口管理、IPC通信、系统集成等核心功能
 */
class RickPanApp {
  private mainWindow: BrowserWindow | null = null
  private tray: Tray | null = null
  private isDev = process.env.NODE_ENV === 'development'

  constructor() {
    this.initApp()
  }

  /**
   * 初始化应用
   */
  private initApp() {
    // 设置应用用户模型ID（Windows）
    if (process.platform === 'win32') {
      app.setAppUserModelId('com.rickpan.app')
    }

    // 应用准备就绪
    app.whenReady().then(() => {
      this.createWindow()
      this.setupIPC()
      this.setupMenu()
      this.setupTray()
      this.setupGlobalShortcuts()
      this.setupAutoUpdater()
    })

    // 所有窗口关闭时的处理
    app.on('window-all-closed', () => {
      if (process.platform !== 'darwin') {
        // Windows/Linux: 窗口关闭时隐藏到托盘，不退出应用
        console.log('所有窗口已关闭，应用继续在托盘运行')
      }
    })

    // 应用退出前清理
    app.on('before-quit', (event) => {
      if (!app.isQuiting) {
        event.preventDefault()
        app.isQuiting = true

        // 清除用户在线状态
        this.clearUserOnlineStatus().then(() => {
          // 清理全局快捷键
          globalShortcut.unregisterAll()

          if (this.tray) {
            this.tray.destroy()
            this.tray = null
          }

          // 真正退出应用
          app.quit()
        }).catch((error) => {
          console.error('清除在线状态失败，强制退出:', error)
          // 即使失败也要退出
          globalShortcut.unregisterAll()
          if (this.tray) {
            this.tray.destroy()
            this.tray = null
          }
          app.quit()
        })
      }
    })

    // macOS激活应用时重新创建窗口
    app.on('activate', () => {
      if (BrowserWindow.getAllWindows().length === 0) {
        this.createWindow()
      }
    })
  }

  /**
   * 创建主窗口
   */
  private createWindow() {
    // 获取保存的窗口设置
    const windowSettings = settingsManager.getWindowSettings()

    this.mainWindow = new BrowserWindow({
      width: windowSettings.width,
      height: windowSettings.height,
      x: windowSettings.x,
      y: windowSettings.y,
      minWidth: 800,
      minHeight: 600,
      show: false, // 先隐藏，加载完成后显示
      frame: false, // 🔑 禁用原生标题栏，使用自定义标题栏
      icon: join(__dirname, '../build/icon.png'),
      webPreferences: {
        nodeIntegration: false,
        contextIsolation: true,
        enableRemoteModule: false,
        preload: join(__dirname, 'preload.cjs'),
        webSecurity: true
      },
      titleBarStyle: process.platform === 'darwin' ? 'hiddenInset' : 'hidden'
    })

    // 恢复窗口状态
    if (windowSettings.isMaximized) {
      this.mainWindow.maximize()
    }

    if (windowSettings.isAlwaysOnTop) {
      this.mainWindow.setAlwaysOnTop(true)
    }

    // 加载应用内容
    if (this.isDev) {
      this.mainWindow.loadURL('http://localhost:5173')
      this.mainWindow.webContents.openDevTools()
    } else {
      this.mainWindow.loadFile(join(__dirname, '../dist/index.html'))
    }

    // 窗口准备显示时显示窗口
    this.mainWindow.once('ready-to-show', () => {
      this.mainWindow?.show()
      
      if (this.isDev) {
        this.mainWindow?.webContents.openDevTools()
      }
    })

    // 窗口状态变化监听
    this.setupWindowStateListeners()

    // 窗口关闭时的处理
    this.mainWindow.on('close', (event) => {
      if (!app.isQuiting) {
        event.preventDefault()

        // 询问用户是要最小化到托盘还是退出应用
        const { dialog } = require('electron')
        const choice = dialog.showMessageBoxSync(this.mainWindow!, {
          type: 'question',
          buttons: ['最小化到托盘', '退出应用', '取消'],
          defaultId: 0,
          title: 'RickPan',
          message: '您想要最小化到托盘还是退出应用？',
          detail: '最小化到托盘：应用继续在后台运行\n退出应用：完全关闭应用并清除在线状态'
        })

        if (choice === 0) {
          // 最小化到托盘
          this.mainWindow?.hide()
        } else if (choice === 1) {
          // 退出应用
          app.isQuiting = true
          this.clearUserOnlineStatus().then(() => {
            app.quit()
          }).catch(() => {
            app.quit()
          })
        }
        // choice === 2 (取消) 什么都不做
      }
    })
  }

  /**
   * 设置窗口状态监听
   */
  private setupWindowStateListeners() {
    if (!this.mainWindow) return

    // 防抖保存函数
    let saveTimeout: NodeJS.Timeout
    const debouncedSave = () => {
      clearTimeout(saveTimeout)
      saveTimeout = setTimeout(() => {
        this.saveWindowState()
      }, 500) // 500ms防抖
    }

    // 监听窗口大小和位置变化
    this.mainWindow.on('resize', debouncedSave)
    this.mainWindow.on('move', debouncedSave)

    // 监听最大化/还原
    this.mainWindow.on('maximize', () => {
      settingsManager.updateWindowSettings({ isMaximized: true })
    })

    this.mainWindow.on('unmaximize', () => {
      settingsManager.updateWindowSettings({ isMaximized: false })
      debouncedSave() // 还原时保存新的尺寸
    })

    // 监听置顶状态变化
    this.mainWindow.on('always-on-top-changed', (_, isAlwaysOnTop) => {
      settingsManager.updateWindowSettings({ isAlwaysOnTop })
    })
  }

  /**
   * 保存窗口状态
   */
  private saveWindowState() {
    if (!this.mainWindow || this.mainWindow.isMaximized()) return

    const bounds = this.mainWindow.getBounds()
    settingsManager.updateWindowSettings({
      width: bounds.width,
      height: bounds.height,
      x: bounds.x,
      y: bounds.y
    })
  }

  /**
   * 设置IPC通信
   */
  private setupIPC() {
    // 文件操作
    ipcMain.handle('file:select', this.handleFileSelect.bind(this))
    ipcMain.handle('file:selectFolder', this.handleFolderSelect.bind(this))
    ipcMain.handle('file:save', this.handleFileSave.bind(this))

    // 应用控制
    ipcMain.handle('app:minimize', () => this.mainWindow?.minimize())
    ipcMain.handle('app:maximize', () => {
      if (this.mainWindow?.isMaximized()) {
        this.mainWindow.unmaximize()
      } else {
        this.mainWindow?.maximize()
      }
    })
    ipcMain.handle('app:close', () => this.mainWindow?.close())
    ipcMain.handle('app:hide', () => this.mainWindow?.hide())
    ipcMain.handle('app:show', () => {
      this.mainWindow?.show()
      this.mainWindow?.focus()
    })
    ipcMain.handle('app:isMaximized', () => this.mainWindow?.isMaximized() || false)

    // 系统操作
    ipcMain.handle('system:openExternal', (_, url: string) => shell.openExternal(url))
    ipcMain.handle('system:showItemInFolder', (_, path: string) => shell.showItemInFolder(path))

    // 通知
    ipcMain.handle('notification:show', this.handleShowNotification.bind(this))

    // 设置管理
    ipcMain.handle('settings:get', () => settingsManager.getSettings())
    ipcMain.handle('settings:getWindow', () => settingsManager.getWindowSettings())
    ipcMain.handle('settings:getApp', () => settingsManager.getAppSettings())
    ipcMain.handle('settings:getFileManager', () => settingsManager.getFileManagerSettings())
    ipcMain.handle('settings:getAI', () => settingsManager.getAISettings())

    ipcMain.handle('settings:updateWindow', (_, settings) => settingsManager.updateWindowSettings(settings))
    ipcMain.handle('settings:updateApp', (_, settings) => settingsManager.updateAppSettings(settings))
    ipcMain.handle('settings:updateFileManager', (_, settings) => settingsManager.updateFileManagerSettings(settings))
    ipcMain.handle('settings:updateAI', (_, settings) => settingsManager.updateAISettings(settings))

    ipcMain.handle('settings:reset', () => settingsManager.resetSettings())
    ipcMain.handle('settings:export', () => settingsManager.exportSettings())
    ipcMain.handle('settings:import', (_, settingsJson) => settingsManager.importSettings(settingsJson))

    // 窗口控制
    ipcMain.handle('window:toggleAlwaysOnTop', () => {
      if (this.mainWindow) {
        const isOnTop = this.mainWindow.isAlwaysOnTop()
        this.mainWindow.setAlwaysOnTop(!isOnTop)
        return !isOnTop
      }
      return false
    })

    ipcMain.handle('window:setAlwaysOnTop', (_, alwaysOnTop: boolean) => {
      if (this.mainWindow) {
        this.mainWindow.setAlwaysOnTop(alwaysOnTop)
        return alwaysOnTop
      }
      return false
    })

    // 自动更新
    ipcMain.handle('updater:check', () => autoUpdater.checkForUpdatesAndNotify())
    ipcMain.handle('updater:download', () => autoUpdater.downloadUpdate())
    ipcMain.handle('updater:install', () => autoUpdater.quitAndInstall())
  }

  /**
   * 处理文件选择
   */
  private async handleFileSelect() {
    const result = await dialog.showOpenDialog(this.mainWindow!, {
      properties: ['openFile', 'multiSelections'],
      filters: [
        { name: 'All Files', extensions: ['*'] },
        { name: 'Images', extensions: ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'] },
        { name: 'Documents', extensions: ['pdf', 'doc', 'docx', 'txt', 'md'] },
        { name: 'Videos', extensions: ['mp4', 'avi', 'mov', 'wmv', 'flv'] },
        { name: 'Audio', extensions: ['mp3', 'wav', 'flac', 'aac'] }
      ]
    })
    return result.filePaths
  }

  /**
   * 处理文件夹选择
   */
  private async handleFolderSelect() {
    const result = await dialog.showOpenDialog(this.mainWindow!, {
      properties: ['openDirectory']
    })
    return result.filePaths[0] || null
  }

  /**
   * 处理文件保存
   */
  private async handleFileSave(_, data: any, defaultPath?: string) {
    const result = await dialog.showSaveDialog(this.mainWindow!, {
      defaultPath,
      filters: [
        { name: 'All Files', extensions: ['*'] }
      ]
    })
    
    if (!result.canceled && result.filePath) {
      // 这里可以添加文件保存逻辑
      return result.filePath
    }
    return null
  }

  /**
   * 显示关于对话框
   */
  private showAboutDialog() {
    const iconPath = this.isDev
      ? join(__dirname, '../../public/favicon-32x32.png')
      : join(process.resourcesPath, 'app/dist/favicon-32x32.png')

    dialog.showMessageBox(this.mainWindow!, {
      type: 'info',
      title: '关于 RickPan',
      message: 'RickPan',
      detail: `版本: ${app.getVersion()}\n\n企业级云存储解决方案\n支持文件管理、AI助手、工作报告等功能\n\n© 2025 RickPan Team`,
      buttons: ['确定'],
      defaultId: 0,
      icon: iconPath
    })
  }

  /**
   * 处理系统通知
   */
  private handleShowNotification(_: any, options: any) {
    try {
      // 使用Electron的Notification API
      if (Notification.isSupported()) {
        const iconPath = options.icon || (this.isDev
          ? join(__dirname, '../../public/favicon-32x32.png')
          : join(process.resourcesPath, 'app/dist/favicon-32x32.png'))

        const notification = new Notification({
          title: options.title || 'RickPan',
          body: options.body || '',
          icon: iconPath,
          silent: options.silent || false
        })

        // 添加点击事件处理
        notification.on('click', () => {
          this.showMainWindow()

          // 如果有回调动作，执行它
          if (options.action) {
            this.mainWindow?.webContents.send('notification:action', options.action)
          }
        })

        notification.show()

        // 自动关闭通知（可选）
        if (options.autoClose && options.autoClose > 0) {
          setTimeout(() => {
            notification.close()
          }, options.autoClose)
        }
      } else {
        console.warn('系统不支持通知功能')
      }
    } catch (error) {
      console.error('显示通知失败:', error)
    }
  }

  /**
   * 设置应用菜单
   */
  private setupMenu() {
    const template = [
      {
        label: '文件',
        submenu: [
          {
            label: '上传文件',
            accelerator: 'CmdOrCtrl+O',
            click: () => {
              this.handleFileSelect()
            }
          },
          { type: 'separator' },
          {
            label: '退出',
            accelerator: process.platform === 'darwin' ? 'Cmd+Q' : 'Ctrl+Q',
            click: () => {
              app.quit()
            }
          }
        ]
      },

      {
        label: '视图',
        submenu: [
          {
            label: '刷新',
            accelerator: 'F5',
            role: 'reload'
          },
          {
            label: '强制重新加载',
            role: 'forceReload'
          },
          {
            label: '开发者工具',
            role: 'toggleDevTools'
          },
          { type: 'separator' },
          {
            label: '实际大小',
            role: 'resetZoom'
          },
          {
            label: '放大',
            role: 'zoomIn'
          },
          {
            label: '缩小',
            role: 'zoomOut'
          },
          { type: 'separator' },
          {
            label: '全屏',
            role: 'togglefullscreen'
          }
        ]
      },

      {
        label: '窗口',
        submenu: [
          {
            label: '最小化',
            role: 'minimize'
          },
          {
            label: '关闭',
            role: 'close'
          },
          { type: 'separator' },
          {
            label: '置顶',
            type: 'checkbox',
            checked: settingsManager.getWindowSettings().isAlwaysOnTop,
            click: (menuItem: Electron.MenuItem) => {
              this.mainWindow?.setAlwaysOnTop(menuItem.checked)
              settingsManager.updateWindowSettings({ isAlwaysOnTop: menuItem.checked })
            }
          }
        ]
      },
      {
        label: '帮助',
        submenu: [
          {
            label: '快捷键帮助',
            accelerator: 'F1',
            click: () => {
              this.mainWindow?.webContents.send('menu:shortcuts-help')
            }
          },
          {
            label: '用户手册',
            click: () => {
              shell.openExternal('https://rickpan.com/docs')
            }
          },
          {
            label: '反馈问题',
            click: () => {
              shell.openExternal('https://github.com/rickpan/issues')
            }
          },
          { type: 'separator' },
          {
            label: '检查更新',
            click: () => {
              this.mainWindow?.webContents.send('menu:check-updates')
            }
          },
          {
            label: '关于 RickPan',
            click: () => {
              this.showAboutDialog()
            }
          }
        ]
      }
    ]

    const menu = Menu.buildFromTemplate(template as any)
    Menu.setApplicationMenu(menu)
  }

  /**
   * 设置系统托盘
   */
  private setupTray() {
    // 尝试多个图标路径
    const possiblePaths = [
      join(__dirname, '../../public/favicon-32x32.png'),
      join(__dirname, '../../public/pwa-192x192.png'),
      join(__dirname, '../public/favicon-32x32.png'),
      join(process.cwd(), 'public/favicon-32x32.png'),
      join(process.cwd(), 'public/pwa-192x192.png')
    ]

    let trayIconPath = ''

    // 查找存在的图标文件
    for (const path of possiblePaths) {
      try {
        if (require('fs').existsSync(path)) {
          trayIconPath = path
          console.log('找到托盘图标:', path)
          break
        }
      } catch (e) {
        continue
      }
    }

    if (!trayIconPath) {
      console.error('未找到托盘图标文件')
      return
    }

    try {
      console.log('正在创建系统托盘...')
      this.tray = new Tray(trayIconPath)

      const contextMenu = Menu.buildFromTemplate([
        {
          label: '显示 RickPan',
          click: () => {
            console.log('托盘菜单：显示窗口')
            this.showMainWindow()
          }
        },
        { type: 'separator' },
        {
          label: '上传文件',
          click: () => {
            console.log('托盘菜单：上传文件')
            this.handleFileSelect()
          }
        },
        { type: 'separator' },
        {
          label: '关于 RickPan',
          click: () => {
            console.log('托盘菜单：关于')
            this.showAboutDialog()
          }
        },
        {
          label: '退出',
          click: () => {
            console.log('托盘菜单：退出')
            app.isQuiting = true
            this.clearUserOnlineStatus().then(() => {
              app.quit()
            }).catch(() => {
              app.quit()
            })
          }
        }
      ])

      this.tray.setToolTip('RickPan - 企业级云存储')
      this.tray.setContextMenu(contextMenu)

      // 双击托盘图标显示窗口
      this.tray.on('double-click', () => {
        console.log('托盘双击：显示窗口')
        this.showMainWindow()
      })

      // 右键点击事件
      this.tray.on('right-click', () => {
        console.log('托盘右键点击')
        this.tray?.popUpContextMenu()
      })

      console.log('系统托盘创建成功')
    } catch (error) {
      console.error('创建系统托盘失败:', error)
    }
  }

  /**
   * 显示主窗口
   */
  private showMainWindow() {
    if (this.mainWindow) {
      if (this.mainWindow.isMinimized()) {
        this.mainWindow.restore()
      }
      this.mainWindow.show()
      this.mainWindow.focus()
    }
  }

  /**
   * 处理截图上传
   */
  private async handleScreenshot() {
    try {
      this.handleShowNotification(null, {
        title: 'RickPan',
        body: '截图上传功能正在开发中...'
      })
    } catch (error) {
      console.error('截图失败:', error)
    }
  }

  /**
   * 处理全局刷新
   */
  private handleGlobalRefresh() {
    try {
      if (this.mainWindow) {
        // 显示窗口（如果被最小化）
        if (this.mainWindow.isMinimized()) {
          this.mainWindow.restore()
        }
        this.mainWindow.show()
        this.mainWindow.focus()

        // 刷新页面
        this.mainWindow.webContents.reload()

        console.log('执行全局刷新')
      }
    } catch (error) {
      console.error('全局刷新失败:', error)
    }
  }

  /**
   * 设置全局快捷键
   */
  private setupGlobalShortcuts() {
    try {
      // 快速截图上传快捷键
      globalShortcut.register('CommandOrControl+Shift+S', () => {
        this.handleScreenshot()
      })

      // 全局刷新快捷键
      globalShortcut.register('CommandOrControl+Shift+R', () => {
        this.handleGlobalRefresh()
      })

      // F5全局刷新快捷键
      globalShortcut.register('F5', () => {
        this.handleGlobalRefresh()
      })

      console.log('全局快捷键注册成功')
    } catch (error) {
      console.error('注册全局快捷键失败:', error)
    }
  }

  /**
   * 设置自动更新
   */
  private setupAutoUpdater() {
    if (this.isDev) {
      return // 开发环境不启用自动更新
    }

    autoUpdater.checkForUpdatesAndNotify()

    autoUpdater.on('update-available', () => {
      this.mainWindow?.webContents.send('update-available')
    })

    autoUpdater.on('update-downloaded', () => {
      this.mainWindow?.webContents.send('update-downloaded')
    })
  }

  /**
   * 清除用户在线状态
   */
  private async clearUserOnlineStatus(): Promise<void> {
    return new Promise(async (resolve, reject) => {
      try {
        // 从渲染进程获取用户token
        const token = await this.mainWindow?.webContents.executeJavaScript(`
          localStorage.getItem('token');
        `);

        if (!token) {
          console.log('⚠️ 用户未登录，无需清除在线状态');
          resolve();
          return;
        }

        // 使用Node.js http模块调用logout API
        const postData = JSON.stringify({});
        const options = {
          hostname: 'localhost',
          port: 8080,
          path: '/api/auth/logout',
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json',
            'Content-Length': Buffer.byteLength(postData)
          },
          timeout: 5000 // 5秒超时
        };

        const req = http.request(options, (res) => {
          console.log(`在线状态清除请求响应: ${res.statusCode}`);

          let data = '';
          res.on('data', (chunk) => {
            data += chunk;
          });

          res.on('end', () => {
            if (res.statusCode === 200) {
              console.log('✅ 用户在线状态清除成功');
            } else {
              console.log(`⚠️ 在线状态清除响应异常: ${res.statusCode}`);
            }
            resolve();
          });
        });

        req.on('error', (error) => {
          console.error('❌ 清除用户在线状态请求失败:', error.message);
          resolve(); // 即使失败也要resolve，不阻止应用退出
        });

        req.on('timeout', () => {
          console.error('❌ 清除用户在线状态请求超时');
          req.destroy();
          resolve(); // 超时也要resolve
        });

        req.write(postData);
        req.end();

      } catch (error) {
        console.error('❌ 清除用户在线状态失败:', error);
        resolve(); // 异常也要resolve，不阻止应用退出
      }
    });
  }
}

// 创建应用实例
new RickPanApp()

// 扩展app对象类型
declare global {
  namespace Electron {
    interface App {
      isQuiting?: boolean
    }
  }
}
